<template>
  <el-scrollbar height="52vh">
    <div class="product-detail-container">
      <!-- 左侧商品信息 -->
      <div class="left-section">
        <!-- 左1：商品图和描述 -->
        <div class="left-1">
          <div class="product-image">
            <el-carousel :autoplay="false" indicator-position="outside">
              <el-carousel-item v-for="resource in resourcesList" :key="resource.id">
                <img :src="resource.url" alt="资源图" class="resource-image" @click="showImageInDialog(resource.url)" />
              </el-carousel-item>
            </el-carousel>
          </div>
          <div class="product-description">
            <h3>{{ product.name }}</h3>
            <h4>商品描述</h4>
            <p>{{ product.description }}</p>
            <h4>品牌</h4>
            <p>{{ product.brand }}</p>
          </div>
        </div>

        <!-- 左2：商品规格、价格、操作按钮 -->
        <div class="left-2">
          <div class="product-specs">
            <h3>商品规格</h3>
            <el-scrollbar height="300px">
              <div v-for="attribute in attributesList" :key="attribute.id" class="attribute-item">
                <el-radio v-model="selectedAttribute" :label="attribute">
                  <img :src="attribute.attributeImg" alt="属性图" class="attribute-img" @click="showImageInDialog(attribute.attributeImg)" />
                  <span>{{ attribute.attributeName }}</span>
                  <span>￥{{ attribute.price }}</span>
                  <span>库存：{{ attribute.quantity }}</span>
                </el-radio>
              </div>
            </el-scrollbar>

          </div>
          <div class="product-price">
            <h3>价格</h3>
            <p class="price">￥{{ selectedAttribute?.price?selectedAttribute.price:product.price }}</p>
          </div>
          <div class="product-actions">
            <el-button type="primary" @click="goToStore(product.brandId)">进店</el-button>
            <el-button type="success" @click="addToCart">加入购物车</el-button>
            <el-button type="primary" @click="favoriteProduct">收藏商品</el-button>
            <!--        <el-button type="warning" @click="payNow">下单</el-button>-->
          </div>
        </div>
      </div>
      <!-- 右侧 Tab 切换 -->
      <div class="right-section">
        <el-tabs v-model="activeTab" class="tabs">
          <el-tab-pane label="详细描述" name="images">
            <el-scrollbar height="440px">
              <div class="tab-content" v-for="resource in resourcesList" :key="resource.id">
                <img :src="resource.url" alt="商品图" class="image" style="width: 100%;" @click="showImageInDialog(resource.url)" />
              </div>
              <p>
                {{product.detailInfo}}
              </p>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane label="评价" name="reviews">
            <div class="tab-content">
              <h3>评价展示</h3>
              <div v-for="review in commentList" :key="review.id" class="review">
                <p>
                  {{ formatDate(review.createdAt) }}</p>
                <p><strong>{{review.comment}}</strong></p>
                <div v-if="review.url!=null">
                  <img :src="review.url" width="150px" alt="" @click="showImageInDialog(review.url)">
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="优惠券" name="disclaim">
            <div class="tab-content">
              <div v-for="discountInfo in discountList" :key="discountInfo.id" class="review">
                <p>
                  截至{{ formatDate(discountInfo.endDate) }}</p>
                <p><strong>{{discountInfo.discountName}}</strong></p>
                <strong><el-tag type="primary">{{discountInfo.discountType}}优惠</el-tag></strong>
                <strong><el-tag type="success">{{discountInfo.discountStrategy==2?'满减':'折扣'}}</el-tag></strong>
                <el-button
                  :disabled="discountInfo.status==2"
                  type="primary" style="margin-left: 20px" size="small" @click="getDiscountInfo(discountInfo.discountId)">{{discountInfo.status==2?'已领取':'领取'}}</el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </el-scrollbar>

<el-dialog v-model="dialogVisible" title="图片详情" style="margin: 50px auto">
  <img :src="dialogImageUrl" alt="大图" style="width: 100%;" />
</el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted,watch, reactive } from 'vue'
import {
  addCartItem,
  getAttributes,
  getProductResourcesByProductId,
  addToFavorites,
  getProductComment, DiscountAPI
} from '@/common/net/api'
import { ElMessage, ElRadio } from "element-plus";
const dialogVisible = ref(false);
const dialogImageUrl = ref('');
import { useRouter } from 'vue-router';

import moment from 'moment'
import type { DiscountInfo, DiscountQueryParams } from '@/common/types/discountTypes.ts'
const router = useRouter();
const props = defineProps({
  product: {
    type: Object,
    required: true,
    default: () => ({
      imageUrl: '',
      name: '',
      description: '',
      specs: '',
      deliveryAddress: '',
      price: 0,
      reviews: [
        { id: 1, username: '用户1', content: '好评！' },
        { id: 2, username: '用户2', content: '非常满意！' }
      ]
    })
  }
});

let activeTab = ref('images'); // 默认激活的 Tab
let resourcesList: any = ref([]);
let commentList = ref([]);
let discountList = ref([]);
let queryParams = ref<DiscountQueryParams>({
  page: 1,
  size: 10,
  discountType: '',
  productId: undefined,
  status: 1
})
const attributesList = ref([]);
const selectedAttribute = ref(null);
const formatDate = (dateString: any) => {
  return moment(dateString).format('YYYY/MM/DD HH:mm:ss');
};
// 模拟操作按钮的逻辑
const goToStore = (id:number) => {
  const route = router.resolve({ name: 'StoreView', params: { brandId: id } });
  window.open(route.href, '_blank');
};

const addToCart = async () => {
  console.log('addToCart');
  console.log(selectedAttribute)
  try {
    const cartItem = {
      productId: props.product.productId,
      quantity: 1,
      addPrice: selectedAttribute?.price?selectedAttribute.price:props.product.price,
      brandId: props.product.brandId,
      attributeId: selectedAttribute.value.attributeId,
    };
    await addCartItem(cartItem).then(res =>{
      if (res.data.state){
        ElMessage.success('加入购物车成功！');
      }else {
        ElMessage.error('加入购物车失败');
      }
    });
  } catch (error) {
    ElMessage.error('加入购物车失败');
  }
};
//获取优惠内容
async function fetchDiscountList() {
  try {
    console.log('fetchDiscountList');
    const response = await DiscountAPI.getList(queryParams.value);
    console.log(response);
    const res  = await DiscountAPI.getDiscountClaimsByUserId(queryParams.value);

    discountList.value = response.data.data.records;
    console.log(res)
    let userRes:[] = res.data.data;
    userRes.forEach((userItem) => {
      // 在 discountList 中查找是否存在 discountId 与 userItem.discountId 相等的项
      const foundItem = discountList.value.find((listItem) => listItem.discountId === userItem.discountId);
      console.log('-----------')
      console.log(foundItem)
      // 如果找到匹配项，则在该匹配项后面添加一个状态为 2 的新属性
      if (foundItem) {
        foundItem.status = 2;
      }
    });

    console.log(discountList.value); // 输出修改后的 discountList 数组

  } catch (error) {
    ElMessage.error('获取优惠资源失败');
  }
}
async function getDiscountInfo(id:number) {
  try {
    const response = await DiscountAPI.getDiscount(id);
    if (response.data.state) {
      ElMessage.success('获取优惠成功');
    }else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('获取优惠失败');
  }
}
// 获取商品资源
async function fetchProductResources(productId: number) {
  try {
    const response : any = await getProductResourcesByProductId(productId);
    resourcesList.value = response.data.data;
  } catch (error) {
    ElMessage.error('获取商品资源失败');
  }
}
// 获取评论资源
async function fetchProductComment(productId: number) {
  try {
    const response = await getProductComment(productId);
    commentList.value = response.data.data;
  } catch (error) {
    ElMessage.error('获取商品资源失败');
  }
}
// 获取商品属性
async function fetchProductAttributes(productId: number) {
  try {
    const response = await getAttributes(productId);
    attributesList.value = response.data;
    if (attributesList.value.length > 0) {
      selectedAttribute.value = attributesList.value[0]; // 默认选中第一个属性
    }
  } catch (error) {
    ElMessage.error('获取商品属性失败');
  }
}

// 监听 product 的变化，自动调用获取资源和属性的方法
watch(() => props.product, (newProduct) => {
  if (newProduct.productId) {
    queryParams.value.productId = newProduct.productId;
    fetchProductResources(newProduct.productId);
    fetchProductAttributes(newProduct.productId);
    fetchProductComment(newProduct.productId);
    fetchDiscountList()
  }
}, { deep: true, immediate: true });
const showImageInDialog = (url: string) => {
  dialogImageUrl.value = url;
  dialogVisible.value = true;
};
const favoriteProduct = async () => {
  try {
    await addToFavorites(props.product.productId).then(res=>{
      if (res.data.state ) {
        ElMessage.success('收藏商品成功！');
      }else{
        ElMessage.error(res.data.msg);
      }
    });

  } catch (error) {
    ElMessage.error('收藏商品失败');
  }
};
</script>

<style scoped lang="scss">
.product-detail-container {
  display: flex;
  gap: 20px;
}

.left-section {
  flex: 5; // 左侧占比 70%
  display: flex;
  gap: 20px;
}

.left-1{
  flex: 1;
}
.left-2 {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.product-image{
  flex: 2;
}
.product-description {
  flex: 1;
  line-height: 30px;
}

.product-specs,
.product-price {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
}

.product-actions {
  display: flex;
  gap: 10px;
}

.right-section {
  flex: 3; // 右侧占比 30%
}

.tabs {
  width: 100%;
}


.review {
  border-bottom: 1px solid salmon;
  line-height: 30px;
  padding-bottom: 20px;
}

.attribute-item {
  display: flex;
  align-items: center;
  gap: 10px;
  height: 60px;
  .attribute-img {
    width: 50px;
    height: 50px;
    object-fit: cover;
  }
  span{
    font-size: 16px;
    margin: 5px;
  }
}

.resource-image {
  width: 100%;
  height: 100%;
}

.resource-video {
  width: 100%;
  height: auto;
}
</style>
